import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { Photo } from '../entity/photo.entity';

@Provide()
export class PhotoService {
  // 注入 EntityModel

  @InjectEntityModel(Photo)
  photoModel: Repository<Photo>;

  // 数据库写入
  async savePhoto() {
    // create a entity object
    const photo = new Photo();
    photo.name = '张三';
    photo.description = '我是张三';
    photo.filename = 'photo-with-bears.jpg';
    photo.views = 1;
    photo.isPublished = true;

    // save entity
    const photoResult = await this.photoModel.save(photo);

    // save success
    console.log('photo id = ', photoResult.id);

    return photoResult;
  }

  // find
  async findPhotos() {
    // find All
    const allPhotos1 = await this.photoModel.find({});
    console.log('All photos from the db: ', allPhotos1);

    // find first
    const firstPhoto = await this.photoModel.findOne({
      where: {
        id: 1,
      },
    });
    console.log('First photo from the db: ', firstPhoto);

    // find one by name
    const meAndBearsPhoto = await this.photoModel.findOne({
      where: { name: 'Me and Bears' },
    });
    console.log('Me and Bears photo from the db: ', meAndBearsPhoto);

    // find by views
    const allViewedPhotos = await this.photoModel.find({
      where: { views: 1 },
    });
    console.log('All viewed photos: ', allViewedPhotos);

    const allPublishedPhotos = await this.photoModel.find({
      where: { isPublished: true },
    });
    console.log('All published photos: ', allPublishedPhotos);

    // find and get count
    const [allPhotos, photosCount] = await this.photoModel.findAndCount({});
    console.log('All photos: ', allPhotos);
    console.log('Photos count: ', photosCount);
  }
}
